<template>
  <div class="home">
    <navbar></navbar>
    <van-tabs v-model="active" swipeable sticky>
        <van-tab v-for="(item,index) in category" :key="index" :title="item.title">
            <van-list
            v-model="item.loading"
            :finished="item.finished"
            finished-text="没有更多了"
            @load="onLoad"
            :immediate-check="false"
            >
                <div class="detailparent">
                    <detail class="detailitem" :detailitem="categoryitem" v-for="(categoryitem,categoryindex) in item.list" :key="categoryindex" />
                </div>
            </van-list>
        </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import Navbar from '@/components/common/Navbar'
import Detail from '@/views/Detail'
export default {
    data () {
        return {
            category:[],
            active: 0
        }
    },
    components: {
        Navbar,
        Detail
    },
    methods: {
        async selectCategory () {
            const res = await this.$http.get('/category')
            this.changeCategory(res.data)
        },
        changeCategory (data) {
            const caregory1 = data.map((item,index) => {
                item.list = []
                item.page = 0
                item.finished = false
                item.loading = false
                item.pagesize = 10
                return item
            })
            this.category = caregory1
            this.selectArticle()
        },
        async selectArticle () {
            const categoryitem = this.caregoryItem()
            const res = await this.$http.get('/detail/' + categoryitem._id,{
                params:{
                    page:categoryitem.page,
                    pagesize:categoryitem.pagesize
                }
            })
            categoryitem.list.push(...res.data)
            categoryitem.loading = false
            if(res.data.length < categoryitem.pagesize) {
                categoryitem.finished = true
            }
        },
        caregoryItem () {
            const categoryitem = this.category[this.active]
            return categoryitem
        },
        onLoad () {
            const categoryitem = this.caregoryItem()
            setTimeout( () => {
                categoryitem.page += 1
                this.selectArticle()
            },1000)
        }
    },
    watch:{
        active () {
            this.selectArticle()
        }
    },
    created () {
        this.selectCategory()
    }
}
</script>

<style lang="stylus" scoped>
.home
  background-color white
  .detailparent
    display flex
    flex-wrap  wrap
    justify-content space-around
    .detailitem
      margin 5px 0
      width 45%
</style>